#!/usr/bin/env python
import redis
import json
from tasks import app
import time
import uuid

# Redis连接配置
REDIS_URL = 'redis://:Hewenyu1994@121.5.249.100:6379/0'
redis_client = redis.from_url(REDIS_URL)

def inspect_redis_keys():
    """检查Redis中的所有键"""
    print("=== Redis Keys ===")
    for key in redis_client.keys('*'):
        key_type = redis_client.type(key).decode('utf-8')
        print(f"Key: {key.decode('utf-8')}, Type: {key_type}")
        
        if key_type == 'list':
            list_items = redis_client.lrange(key, 0, -1)
            for i, item in enumerate(list_items):
                try:
                    # 尝试解析为JSON
                    decoded = json.loads(item)
                    print(f"  List item {i}: {json.dumps(decoded, indent=2)}")
                except:
                    # 如果不是JSON，直接打印
                    print(f"  List item {i}: {item}")
        
        elif key_type == 'hash':
            hash_items = redis_client.hgetall(key)
            print(f"  Hash contents: {hash_items}")
            for k, v in hash_items.items():
                try:
                    # 尝试解析为JSON
                    decoded = json.loads(v)
                    print(f"  Hash field {k.decode('utf-8')}: {json.dumps(decoded, indent=2)}")
                except:
                    print(f"  Hash field {k.decode('utf-8')}: {v}")

def send_celery_task():
    """发送一个Celery任务并返回task_id"""
    # 生成唯一的任务ID
    task_id = str(uuid.uuid4())
    
    # 发送任务 - 注意观察args和properties是如何设置的
    result = app.send_task(
        'tasks.add',
        args=[10, 20],
        task_id=task_id
    )
    
    print(f"Task sent with ID: {result.id}")
    return result.id

def check_task_message_format(task_id):
    """查看特定任务ID的消息结构"""
    # 等待一点时间让任务被处理
    time.sleep(1)
    
    # 检查任务结果
    result_key = f'celery-task-meta-{task_id}'
    if redis_client.exists(result_key):
        result_data = redis_client.get(result_key)
        try:
            result_json = json.loads(result_data)
            print(f"Task result: {json.dumps(result_json, indent=2)}")
        except:
            print(f"Task result (raw): {result_data}")
    else:
        print(f"No result found for task {task_id}")

def main():
    """主函数"""
    # 先清理Redis中的celery相关键，避免干扰
    print("Clearing existing Celery keys...")
    for key in redis_client.keys('celery*'):
        redis_client.delete(key)
    
    # 检查Redis初始状态
    print("\n=== Initial Redis State ===")
    inspect_redis_keys()
    
    # 发送任务
    print("\n=== Sending Celery Task ===")
    task_id = send_celery_task()
    
    # 立即检查Redis状态（在任务执行前）
    print("\n=== Redis State After Sending Task ===")
    inspect_redis_keys()
    
    # 检查任务消息格式
    print("\n=== Task Message Format ===")
    check_task_message_format(task_id)
    
    # 任务执行后检查Redis状态
    print("\n=== Final Redis State ===")
    inspect_redis_keys()

if __name__ == "__main__":
    main()
    print("\nDone.") 